/*
 * @Author: wwssaabb
 * @Date: 2021-12-09 14:47:17
 * @LastEditTime: 2021-12-09 15:59:21
 * @FilePath: \handwritten-code\main\图片懒加载.js
 */

//图片懒加载
/* 
  1.图片加载完后移除事件监听
  2.加载完的图片从imgList移除
*/

let imgList = [...document.querySelectorAll('img')]
let len = imgList.length

const imgLazyLoad = (function () {
  let count = 0

  return function () {
    let deleteIndexList = []
    imgList.forEach((img, index) => {
      let rect = img.getBoundingClientRect()
      if (rect.top < window.innerHeight) {
        console.log('index', '显示', img.dataset)
        img.src = img.dataset.src
        deleteIndexList.push(index)
        count++
        if (count === len) document.removeEventListener('scroll', imgLazyLoad)
      }
    })
    imgList = imgList.filter((img, index) => !deleteIndexList.includes(index))
  }
})()

document.addEventListener('scroll', imgLazyLoad)